// https://leetcode.cn/problems/merge-two-sorted-lists/submissions/555384699/
 class ListNode {
    int val;
    ListNode next;
    ListNode() {}
    ListNode(int val) { this.val = val; }
    ListNode(int val, ListNode next) { this.val = val; this.next = next; }
}

class Solution {
    public ListNode mergeTwoLists(ListNode list1, ListNode list2) {
        if (list1 == null) return list2;
        if (list2 == null) return list1;
        ListNode cur1 = list1;
        ListNode cur2 = list2;
        ListNode newHead = null;
        ListNode curTail = null;

        while (cur1 != null && cur2 != null) {
            if (cur1.val < cur2.val) {
                if (curTail == null) {
                    newHead = cur1;
                    curTail = cur1;
                }else {
                    curTail.next = cur1;
                    curTail = cur1;
                }
                cur1 = cur1.next;
            }else {
                if (curTail == null) {
                    newHead = cur2;
                    curTail = cur2;
                }else {
                    curTail.next = cur2;
                    curTail = cur2;
                }
                cur2 = cur2.next;
            }
        }
        if (cur1 == null) {
            curTail.next = cur2;
        }
        if (cur2 == null) {
            curTail.next = cur1;
        }
        return newHead;
    }
}